import { defineStore } from "pinia";
import { reactive, ref, shallowRef } from "vue";
import { _login, _info } from "@/api/login"

import { setLol, getLol } from "@/utils/local";

export let useUserStore = defineStore("userStore", () => {
    let role = ref<string | null>(JSON.parse(getLol('role')!))
    let token = ref<string | null>(JSON.parse(getLol('tk')!))
    let userInfo = shallowRef<any>({})

    // 登录函数
    let store_login = (formData: loginData) => {
        return new Promise((resolve, reject) => {
            _login(formData).then((res) => {
                // 把role和token值存在仓库
                role.value = res.data.role
                token.value = res.data.token

                // // 存储role和token到本地
                setLol("tk", token.value)
                setLol("role", role.value)

                if (res.data.code == 0) {
                    resolve("登录成功！")
                }
            })
        })
    }

    // 获取用户信息
    let getInfo = () => {
        _info().then(res => {
            console.log(35, res);
            userInfo.value = res.data.userInfo
        })
    }


    return {
        role,
        token,
        userInfo,
        store_login,
        getInfo
    }
})
